package byggeTegning.geometry;

//import DEBUGGING.*;  // Search for DEBUG.<INFO|TRACE| ... >

import javax.media.j3d.*;
import javax.vecmath.*;

// ********************************************************************
// *** CLASS: PolyBody
// ********************************************************************
public class PolyBody extends Shape3D
{
  private static final int vertexFormat
          = GeometryArray.COORDINATES
          | GeometryArray.NORMALS
          | GeometryArray.TEXTURE_COORDINATE_2;
  
  private static final Point2f texCoord[] // SKAL RETTES OPP SENERE
          = { new Point2f(0.0f, 0.0f),
              new Point2f(0.5f, 0.0f),
              new Point2f(0.5f, 0.5f),
              new Point2f(0.0f, 0.5f),
            };
    

  // ******************************************************************
  // *** CONSTRUCTOR: PolyBody
  // ******************************************************************
  /**
  * @param p back face closed polygon. Forside: punktene nevnes 'mot klokka'
  * @param q front face closed polygon. Forside: punktene nevnes 'mot klokka'
  */
  public PolyBody(Point3f[] p,Point3f[] q)
  { int i,face;
    int nFace=Math.min(p.length,q.length)-1;
    int N=nFace*4;
//    ASSERT(p.length==q.length);
//    ASSERT(p[0].equals(p[nFace]));
//    ASSERT(q[0].equals(q[nFace]));
    
    
    Point3f[] verts=new Point3f[N]; // firkanter
    int j=0;
    for(i=1;i<=nFace;i++)
    {
//      DEBUG.INFO("TEST! N="+N+", nFace="+nFace+", i="+i+", j="+j);
      verts[j++]=q[i];
      verts[j++]=q[i-1];
      verts[j++]=p[nFace-i+1];
      verts[j++]=p[nFace-i];
    }
    QuadArray tetra = new QuadArray(N,vertexFormat);
    tetra.setCoordinates(0, verts);

    for(i=0;i<N;i++) tetra.setTextureCoordinate(i, texCoord[i%4]);

    Vector3f normal=new Vector3f();
    Vector3f v1=new Vector3f();
    Vector3f v2=new Vector3f();
    Point3f[] pts=new Point3f[4];
    for(i=0;i<4;i++) pts[i]=new Point3f();
    for(face=0;face<nFace;face++)
    { tetra.getCoordinates(face*4,pts);
      v1.sub(pts[1],pts[0]);
      v2.sub(pts[2],pts[0]);
      normal.cross(v1,v2);
      normal.normalize();
      for(i=0;i<4;i++) tetra.setNormal((face*4 + i),normal);
    }
    
    this.setGeometry(tetra);
    this.setAppearance(new Appearance());

  }
  
}